package com.smart.manager.member.repository;

import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.RandomUtil;
import com.smart.common.entities.constant.SocKetTips;
import com.smart.manager.member.entities.bodys.RMemberMaterialCombinePig;
import com.smart.manager.member.entities.enums.PigCombineStatus;
import com.smart.manager.member.entities.models.MemberMaterialCombinePig;
import com.smart.manager.member.entities.models.MemberMaterialPig;
import com.smart.manager.member.entities.models.MemberRelationFriend;
import com.smart.manager.member.entities.models.query.QMemberMaterialCombinePig;
import com.smart.manager.member.entities.models.query.QMemberMaterialPig;
import com.smart.manager.member.entities.views.MemberView;
import com.smart.manager.product.entities.enums.PigStatus;
import com.smart.service.remind.RemindService;
import com.smart.service.socket.WebSocket;
import lombok.RequiredArgsConstructor;
import lombok.extern.log4j.Log4j2;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Optional;


/**
 * 玩家猪猪
 * @author leo
 * @date 2023/09/22
 */
@Service
@Log4j2
@RequiredArgsConstructor
public class MemberMaterialPigCombineRepository {

    private final MemberFriendRepository memberFriendRepository;
    private final RemindService remindService;
    private final WebSocket webSocket;

    /**
     * 申请合养
     */
    public void addCombine(Long id,RMemberMaterialCombinePig.AddBody body){

        Optional<MemberMaterialCombinePig> combinePig = new QMemberMaterialCombinePig().member.id.eq(id).closeMember.id.eq(body.getMember()).status.eq(PigCombineStatus.VIEW).codePig.eq(body.getCode()).findOneOrEmpty();
        Assert.isTrue(combinePig.isEmpty(),"您已经申请过了,请耐心等待好友回复!");
        Optional<MemberMaterialPig> orEmpty = new QMemberMaterialPig()
                .code.eq(body.getCode()).closeMember.isNull()
                .status.in(PigStatus.NORMAL, PigStatus.WAIT)
                .setMaxRows(1).setMaxRows(1).findOneOrEmpty();
        Assert.isFalse(orEmpty.isEmpty(),"您选中的猪仔不符合合养条件!");
        //验证是否是好友!
        Optional<MemberRelationFriend> friends = memberFriendRepository.isFriends(id, body.getMember());
        Assert.isFalse(friends.isEmpty(),"你们还是不好友请添加好友后操作");
        String code = String.format("HY%s%s", DateUtil.format(DateUtil.date(), DatePattern.PURE_DATETIME_PATTERN), RandomUtil.randomNumbers(3));
        MemberMaterialPig pig = orEmpty.get();
        new MemberMaterialCombinePig()
                .setCode(code)
                .setCodePig(pig.getCode())
                .setMember(pig.getMember())
                .setCloseMember(new MemberView().setId(body.getMember()))
                .setPigLevel(pig.getPigLevel()).setName(pig.getName())
                .setStatus(PigCombineStatus.VIEW).insert();
//        log.warn(pig.getPigLevel());

        //站内消息
        remindService.sendInsideCoCultureMsg(body.getMember(),pig);
        //socket消息
        webSocket.sendOneMessage(body.getMember(), SocKetTips.cooperatePigApp);
    }


    /**
     * 获取邀请我合养的
     * @param id
     * @return {@link List}<{@link MemberMaterialCombinePig}>
     */
    public List<MemberMaterialCombinePig> getCombinePigInfo(Long id){
        return new QMemberMaterialCombinePig().or().closeMember.id.eq(id).member.id.eq(id).endOr().findList();
    }

    /**
     * 处理合养数据
     * @param id member
     */
    public void dispose(Long id,RMemberMaterialCombinePig.DisposeBody body){
        Optional<MemberMaterialCombinePig> orEmpty = new QMemberMaterialCombinePig().code.eq(body.getCode()).closeMember.eq(new MemberView().setId(id)).findOneOrEmpty();
        Assert.isFalse(orEmpty.isEmpty(),"未找到合养请求!");
        MemberMaterialCombinePig combinePig = orEmpty.get().setStatus(body.getStatus());
        if (combinePig.getStatus().equals(PigCombineStatus.AGREE)){
            Optional<MemberMaterialPig> pig = new QMemberMaterialPig().code.eq(combinePig.getCodePig()).closeMember.isNull().findOneOrEmpty();
            pig.ifPresent(memberMaterialPig -> memberMaterialPig.setCloseMember(new MemberView().setId(id)).update());
            Assert.isFalse(pig.isEmpty(),"当前猪仔已经合其他玩家合养了!");
            combinePig.setStatus(PigCombineStatus.AGREE).update();
            Optional<MemberRelationFriend> friends = memberFriendRepository.isFriends(id, combinePig.getMember().getId());
            Assert.isFalse(friends.isEmpty(),"你们还是不好友请添加好友后操作");
            friends.get().setPartner(true).update();

            remindService.sendInsideCoCultureAgreeMsg(combinePig.getCloseMember().getId(),pig.get());
            remindService.sendInsideCoCultureAgreeMsg(combinePig.getMember().getId(),pig.get());
            //socket消息
            webSocket.sendOneMessage(combinePig.getMember().getId(),SocKetTips.cooperatePigSucceed);
            //发送通知
            return;
        }else if (combinePig.getStatus().equals(PigCombineStatus.REFUSE)){
            combinePig.setStatus(PigCombineStatus.REFUSE).update();
            //socket消息
            webSocket.sendOneMessage(combinePig.getMember().getId(),SocKetTips.cooperatePigSucceed);
            //发送通知
            return;
        }
        combinePig.setStatus(PigCombineStatus.OVERDUE).update();
    }



}
